function createTextNode(text) {
    return {
        type: "TEXT_ELEMENT",
        props: {
            nodeValue: text,
            children: []
        }
    }
}

function createElement(type, props, ...children) {
    return {
        type,
        props: {
            ...props,
            children: children.map((child) => {
                return typeof child === "string" ? createTextNode(child) : child
            })
        }
    }
}

function render(el, container) {
    const dom = 
        el.type === "TEXT_ELEMENT"
            ? document.createTextNode("")
            : document.createElement(el.type)

    Object.keys(el.props).forEach((key)=>{
        if(key !== "children"){
            dom[key] = el.props[key]
        }
    })

    const children = el.props.children
    children.forEach((child) => {
        render(child, dom)
    })

    container.append(dom)
}

function preforWorkOfUnit(fiber) {
    // 创建节点
    const dom = 
        fiber.type === "TEXT_ELEMENT"
            ? document.createTextNode("")
            : document.createElement(fiber.type)

    // 处理 props
    Object.keys(fiber.props).forEach((key)=>{
        if(key !== "children"){
            dom[key] = fiber.props[key]
        }
    })

    // 树 => 链表

    // 返回下一个任务
    if(fiber.child) {
        return fiber.child
    }

    if(fiber.sibling) {
        return fiber.sibling
    }

    return fiber.parent.sibling
}

// 任务调度器
function workLoop(deadline) {
    let shouldYield = false
    while (!shouldYield && nextWorkOfUnit) {
        nextWorkOfUnit = preforWorkOfUnit(nextWorkOfUnit)
        shouldYield = deadline.timeRemaining() < 1
    }

    requestIdleCallback(workLoop)
}

requestIdleCallback(workLoop)

const React = {
    render,
    createElement,
}

export default React